"""
代码推荐API服务
提供HTTP接口来访问基于Neo4j的代码推荐功能
"""

import os
import json
from typing import Dict, Any
from flask import Flask, request, jsonify
from flask_cors import CORS
from code_recommender import CodeRecommender, get_driver

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 全局推荐器实例
recommender = None


def init_recommender():
    """初始化推荐器"""
    global recommender
    if recommender is None:
        driver = get_driver()
        recommender = CodeRecommender(driver)


@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        "status": "healthy",
        "service": "code_recommendation_api",
        "version": "1.0.0"
    })


@app.route('/recommendations/function', methods=['POST'])
def get_function_recommendations():
    """
    获取函数推荐
    
    请求体:
    {
        "function_name": "main",
        "context_file": "src/main.cpp",  # 可选
        "limit": 10
    }
    """
    try:
        data = request.get_json()
        if not data or 'function_name' not in data:
            return jsonify({"error": "缺少function_name参数"}), 400
        
        function_name = data['function_name']
        context_file = data.get('context_file')
        limit = data.get('limit', 10)
        
        init_recommender()
        recommendations = recommender.get_function_recommendations(
            function_name, context_file, limit
        )
        
        return jsonify({
            "success": True,
            "data": recommendations,
            "count": len(recommendations)
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/recommendations/next-calls', methods=['POST'])
def get_next_function_calls():
    """
    获取下一个函数调用建议
    
    请求体:
    {
        "function_name": "main",
        "limit": 5
    }
    """
    try:
        data = request.get_json()
        if not data or 'function_name' not in data:
            return jsonify({"error": "缺少function_name参数"}), 400
        
        function_name = data['function_name']
        limit = data.get('limit', 5)
        
        init_recommender()
        next_calls = recommender.get_next_function_calls(function_name, limit)
        
        return jsonify({
            "success": True,
            "data": next_calls,
            "count": len(next_calls)
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/recommendations/signatures', methods=['POST'])
def get_function_signature_suggestions():
    """
    获取函数签名建议
    
    请求体:
    {
        "function_name": "process",
        "limit": 5
    }
    """
    try:
        data = request.get_json()
        if not data or 'function_name' not in data:
            return jsonify({"error": "缺少function_name参数"}), 400
        
        function_name = data['function_name']
        limit = data.get('limit', 5)
        
        init_recommender()
        signatures = recommender.get_function_signature_suggestions(function_name, limit)
        
        return jsonify({
            "success": True,
            "data": signatures,
            "count": len(signatures)
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/recommendations/context', methods=['POST'])
def get_context_aware_recommendations():
    """
    获取上下文感知的推荐
    
    请求体:
    {
        "current_file": "src/main.cpp",
        "current_line": 42,
        "limit": 10
    }
    """
    try:
        data = request.get_json()
        if not data or 'current_file' not in data or 'current_line' not in data:
            return jsonify({"error": "缺少current_file或current_line参数"}), 400
        
        current_file = data['current_file']
        current_line = data['current_line']
        limit = data.get('limit', 10)
        
        init_recommender()
        recommendations = recommender.get_context_aware_recommendations(
            current_file, current_line, limit
        )
        
        return jsonify({
            "success": True,
            "data": recommendations,
            "count": len(recommendations)
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/recommendations/popular', methods=['POST'])
def get_popular_functions():
    """
    获取受欢迎的函数
    
    请求体:
    {
        "file_pattern": "src/",  # 可选
        "limit": 20
    }
    """
    try:
        data = request.get_json() or {}
        file_pattern = data.get('file_pattern')
        limit = data.get('limit', 20)
        
        init_recommender()
        popular = recommender.get_popular_functions(file_pattern, limit)
        
        return jsonify({
            "success": True,
            "data": popular,
            "count": len(popular)
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/search/functions', methods=['POST'])
def search_functions():
    """
    搜索函数
    
    请求体:
    {
        "query": "process",
        "limit": 10
    }
    """
    try:
        data = request.get_json()
        if not data or 'query' not in data:
            return jsonify({"error": "缺少query参数"}), 400
        
        query = data['query']
        limit = data.get('limit', 10)
        
        init_recommender()
        # 使用函数签名建议来实现搜索功能
        results = recommender.get_function_signature_suggestions(query, limit)
        
        return jsonify({
            "success": True,
            "data": results,
            "count": len(results)
        })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/stats', methods=['GET'])
def get_database_stats():
    """获取数据库统计信息"""
    try:
        init_recommender()
        driver = get_driver()
        
        with driver.session() as session:
            # 获取函数总数
            function_count_query = "MATCH (f:Function) RETURN count(f) as function_count"
            function_count = session.run(function_count_query).single()["function_count"]
            
            # 获取调用关系总数
            call_count_query = "MATCH ()-[c:CALLS]->() RETURN count(c) as call_count"
            call_count = session.run(call_count_query).single()["call_count"]
            
            # 获取文件总数
            file_count_query = """
            MATCH (f:Function) 
            WITH DISTINCT f.file as file 
            RETURN count(file) as file_count
            """
            file_count = session.run(file_count_query).single()["file_count"]
            
            return jsonify({
                "success": True,
                "data": {
                    "function_count": function_count,
                    "call_count": call_count,
                    "file_count": file_count
                }
            })
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.errorhandler(404)
def not_found(error):
    return jsonify({"error": "接口不存在"}), 404


@app.errorhandler(500)
def internal_error(error):
    return jsonify({"error": "服务器内部错误"}), 500


if __name__ == '__main__':
    # 从环境变量获取配置
    host = os.getenv('API_HOST', '0.0.0.0')
    port = int(os.getenv('API_PORT', 5000))
    debug = os.getenv('API_DEBUG', 'False').lower() == 'true'
    
    print(f"启动代码推荐API服务...")
    print(f"服务地址: http://{host}:{port}")
    print(f"调试模式: {debug}")
    
    app.run(host=host, port=port, debug=debug)
